/*
 * @(#)OnlineUserAction.java
 * 2011-5-17 下午10:41:38
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.accountmng.web;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;

import com.qyxx.platform.common.json.JsonOutput;
import com.qyxx.platform.common.module.web.CrudActionSupport;
import com.qyxx.platform.common.module.web.FormatMessage;
import com.qyxx.platform.common.module.web.Messages;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.utils.web.ServletUtils;
import com.qyxx.platform.common.utils.web.struts2.Struts2Utils;
import com.qyxx.platform.sysmng.accountmng.entity.OnlineUser;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.accountmng.service.AccountManager;
import com.qyxx.platform.sysmng.accountmng.service.OnlineUserManager;
import com.qyxx.platform.sysmng.utils.Constants;


/**
 *  在线用户管理
 *  @author gxj
 *  @version 1.0
 *  @since 1.6 2011-5-17 下午10:41:38
 */
@Namespace("/sys/account")
public class OnlineUserAction extends CrudActionSupport<OnlineUser> {

	private static final long serialVersionUID = 61811211453595858L;
	
	private OnlineUserManager onlineUserManager;
	
	private AccountManager accountManager;
	
	//-- 页面属性 --//
	private Long id;
	private OnlineUser entity;
	private Long[] ids;
	
	private String userName;
	
	private String userPass;
	
	private Md5PasswordEncoder md5 = new Md5PasswordEncoder();
	
	/**
	 * @param onlineUserManager
	 */
	@Autowired
	public void setOnlineUserManager(OnlineUserManager onlineUserManager) {
		this.onlineUserManager = onlineUserManager;
	}

	/**
	 * @return accountManager
	 */
	public AccountManager getAccountManager() {
		return accountManager;
	}


	
	/**
	 * @param accountManager
	 */
	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}


	/**
	 * @param id
	 */
	public void setId(Long id) {
		this.id = id;
	}

	
	/**
	 * @param ids
	 */
	public void setIds(Long[] ids) {
		this.ids = ids;
	}

	/**
	 * @return userName
	 */
	public String getUserName() {
		return userName;
	}

	
	/**
	 * @param userName
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}

	
	/**
	 * @return userPass
	 */
	public String getUserPass() {
		return userPass;
	}

	
	/**
	 * @param userPass
	 */
	public void setUserPass(String userPass) {
		this.userPass = userPass;
	}

	@Override
	public OnlineUser getModel() {
		return entity;
	}

	@Override
	public String list() throws Exception {
		return SUCCESS;
	}
	
	@JsonOutput
	public String queryList() throws Exception {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		/*//设置默认排序方式
		if (!pager.isOrderBySetted()) {
			pager.setOrderBy("id");
			pager.setOrder(Page.ASC);
		}*/
		pager = onlineUserManager.searchOnlineUser(pager, filters);
		Struts2Utils.renderJson(pager);
		return null;
	}

	@Override
	public String input() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String save() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String view() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@JsonOutput
	@Override
	public String delete() throws Exception {
		onlineUserManager.removeOnlineUsers(ids);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = onlineUserManager.getOnlineUser(id);
		} else {
			entity = new OnlineUser();
		}
	}
	
	/**
	 * 检查用户是否已经登录
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String checkUserIsLogin() throws Exception {
			User user = accountManager.findUserByLoginName(userName);
			FormatMessage fm = new FormatMessage();
			if (user == null) {
				fm.setFlag(Messages.ERROR);
				fm.setMsg("用户" + userName + " 不存在");
			} else {
				if(Constants.DISABLED.equals(user.getStatus())) {
					fm.setFlag(Messages.ERROR);
					fm.setMsg("用户" + userName + "已经被禁用");
				} else {
					String encodePass = md5.encodePassword(userPass, user.getLoginName());
					if(!user.getPassword().equals(encodePass)) {
						fm.setFlag(Messages.ERROR);
						fm.setMsg("密码输入不正确");
					} else {
						List<OnlineUser> ouList = onlineUserManager.searchOnlineUser("loginUsername", user.getLoginName());
						int maxLoginUsers = NumberUtils.toInt(String.valueOf(user.getAlledyerror()),1);
						if(null != ouList && ouList.size() >= maxLoginUsers) {
							StringBuffer msgSb = new StringBuffer();
							msgSb.append("用户" + userName + "已登录：<br/>");
							for(OnlineUser ou : ouList) {
								String msg = "登录地址为" + ou.getLoginIp() + "，登录时间为：" + ou.getLoginTime() +"<br/>";
								msgSb.append(msg);
							}
							fm.setFlag(Messages.FAIL);
							fm.setMsg(msgSb.toString());
						} else {
							boolean isContinue = true;
							//检查用户是否绑定IP地址
							if(Constants.DISABLED.equals(user.getRemoteLogin())) {
								//不允许远程访问+绑定IP为空值，需要检查IP地址
								String ipAddr = ServletUtils.getIpAddr(Struts2Utils.getRequest());
								if(StringUtils.isNotBlank(user.getBindIp())) {//绑定IP访问
									if(!user.getBindIp().equals(ipAddr)) {//不相等
										String msg = "登录IP地址与用户信息中绑定的IP地址不一致，不允许在本机登录";
										fm.setFlag(Messages.ERROR);
										fm.setMsg(msg);
										isContinue = false;
									}
								} else {//只要内网地址即可访问，外网地址禁止访问
									if(!ServletUtils.isInnerIp(ipAddr)) {
										String msg = "该账户不允许外网访问，只允许内网访问";
										fm.setFlag(Messages.ERROR);
										fm.setMsg(msg);
										isContinue = false;
									}
								}
							}
							if(isContinue) {
								fm.setMsg(user.getId());
							}
						}
					}
				}
		}
		formatMessage.setMsg(fm);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 移除登录用户
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String removeLoginUser() throws Exception {
		User user = accountManager.findUserByLoginName(userName);
		if(user != null) {
			onlineUserManager.removeOnlineUserByUserName(user.getLoginName());
		}
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	
	/**
	 * 检查是否内网地址
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String checkInnerIp() throws Exception {
		String ipAddr = ServletUtils.getIpAddr(Struts2Utils.getRequest());
		formatMessage.setMsg(ServletUtils.isInnerIp(ipAddr));
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	

}
